package com.jl.encrypt.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import java.util.Random;

/**
 * res对称加密
 */
public class AESUtils {

    /**
     * 获取密钥
     *
     * @return
     */
    public static String getKey() {
        byte[] encoded = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        return Base64.encode(encoded);
    }

    /**
     * 加密
     *
     * @param str
     * @param key
     * @return
     */
    public static String encode(String str, String key, String iv) {
        cn.hutool.crypto.symmetric.AES aes = new cn.hutool.crypto.symmetric.AES("CBC", "PKCS7Padding",
                key.getBytes(),
                iv.getBytes());
        byte[] encrypt = aes.encrypt(str);
        return Base64.encode(encrypt);
    }

    /**
     * 解密
     *
     * @param str
     * @param key
     * @return
     */
    public static String decode(String str, String key, String iv) {
        cn.hutool.crypto.symmetric.AES aes = new cn.hutool.crypto.symmetric.AES("CBC", "PKCS7Padding",
                key.getBytes(),
                iv.getBytes());
        return aes.decryptStr(Base64.decode(str), CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 获取随机数
     *
     * @param length 长度
     * @return
     */
    public static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }

}
